package temp;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangxi created on 2021/6/27 17:58
 * @version v1.0
 */
public class MultiPrint02 implements Runnable {

    private Lock lock;

    private Condition cur;

    private Condition next;

    private char c;

    private int count;

    public MultiPrint02(Lock lock, Condition cur, Condition next, char c, int count) {
        this.lock = lock;
        this.cur = cur;
        this.next = next;
        this.c = c;
        this.count = count;
    }

    @Override
    public void run() {
        try {
            lock.lock();
            for (int i = 0; i < count; i++) {
                System.out.print(c + " ");
                next.signal();
                try {
                    cur.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Lock lock = new ReentrantLock();
        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();
        Condition conditionC = lock.newCondition();
        Thread thread1 = new Thread(new MultiPrint02(lock, conditionA, conditionB, 'A', 3));
        thread1.start();

        Thread.sleep(10);

        Thread thread2 = new Thread(new MultiPrint02(lock, conditionB, conditionC, 'B', 3));
        thread2.start();

        Thread.sleep(10);

        Thread thread3 = new Thread(new MultiPrint02(lock, conditionC, conditionA, 'C', 3));
        thread3.start();
    }
}
